<?php
/**
 * Created by PhpStorm.
 * User: zd
 * Date: 2018/12/5
 * Time: 15:13
 */

namespace app\api\service;

use \app\api\model\Message as MessageModel;
use \app\api\model\User;
use app\common\lib\Redis;
use app\lib\exception\UserException;
use app\server\controller\Push;
use think\Cache;
use think\Config;
use think\Exception;

class Message
{
    const FORMID = 'FORMID';//订单未支付
    /**
     * 添加formid
     * @param $formId
     * @param $wu_id
     * @param $uid
     * @return $this
     */
    public function  createFormId($formId,$t_id,$wu_id,$uid){
        //redis存储formid
       $result = Cache::store('redis')->set('message:t_id:'.$t_id.':wid:'.$wu_id.':uid:'.$uid.':formid:'.time().rand(1,100),$formId,7*24*3600);
        return $result;
    }

    /**
     * 获取未读消息
     * @param $wu_id
     * @param $uid
     * @return mixed
     */
    public function getCacheMessage($wu_id,$uid){
        $cardInfo = User::getCardInfo($wu_id);
        $message['id'] =$cardInfo->id;
        $message['userimg'] =$cardInfo->userimg;
        $message['name'] =$cardInfo->name;
        $message['unread'] = 0;
        try{
            $cache =  Cache::connect(Config::get('cache.redis'));
            $card = new Card();
            $message['unread'] = $card->getUnreadList($cache->handler(),$wu_id,$uid);
        }catch (\Exception $exception){
            //报错,j记录
        }
        return $message;
    }

    /**
     * 小程序改变俩天记录查看状态
     * @param $wu_id
     * @param $uid
     * @param $type //状态
     * @return string
     */
    public function changeStatus($wu_id,$uid,$type = ''){
        $messageList=[];
        //移除所有message
        try {
            $cache = Cache::connect(Config::get('cache.redis'));
            if ($type == 'user') {
                $list = $cache->handler()->zRange("message:wid:".$wu_id.":unread:user:".$uid.":list:2", 0, -1);//读取小程序未读消息列表
                if (!empty($list)) {
                    foreach ($list as $item) {
                        $cache->handler()->zDelete("message:wid:".$wu_id.":unread:user:".$uid.":list:2", $item);//删除已读缓存
                        $data = json_decode($item, true);
                        $messageList[] = $data['timeid'];
                    }
                    //消息推送通知CRM用户已读
                    $message = $this->getMassgeInfo($uid);
                    $push = new Push($wu_id);
                    $push->sendToClient($message);
                }
            }elseif ($type == 'workuser'){
                $list = $cache->handler()->zRange("message:wid:".$wu_id.":unread:user:".$uid.":list:1", 0, -1);//读取CRM未读消息列表
                if (!empty($list)) {
                    foreach ($list as $item) {
                        $cache->handler()->zDelete("message:wid:".$wu_id.":unread:user:".$uid.":list:1", $item);//删除已读缓存
                        $data = json_decode($item, true);
                        $messageList[] = $data['timeid'];
                    }
                }
            }
            //改变消息状态
            $message = new MessageModel();
            $message->changeStatus($messageList, $type);
            return true;
        }catch (\Exception $exception){
            //报错,j记录
            return false;
        }
    }
    /**
     * 获取CRM聊天信息列表
     * @param $wu_id
     * @return array|mixed|string
     * @throws UserException
     */
    public function getCord($wu_id){
        $messageList = [];
       //获取用户列表
        try{
            $cache =  Cache::connect(Config::get('cache.redis'));
            $list = $cache->handler()->zRevRange("message:wid:".$wu_id.":user:list",0,-1);//获取聊天用户列表
            if (empty($list)){
               return '';
            }
            foreach ($list as $key=> $item){
                $messageList[$key] = json_decode($cache->handler()->get("message:wid:". $wu_id.":user:".$item.":info"),true);
                //获取用户未读消息
                $messageList[$key]['unread'] = $this->getUnreadList($cache->handler(),$wu_id,$item);
            }
            return $messageList;
        }catch (\Exception $exception){
            throw new UserException([
                'code'=>201,
                'msg'=>'获取聊天信息失败',
                'error_code'=>90000
            ]);
        }
    }
    /**
     * 删除联系人
     * @param $uid
     * @param $wu_id
     * @return bool
     */
    public function deleteUser($uid,$wu_id){
        try{
            $cache = Cache::connect(Config::get('cache.redis'));
            $cache->handler()->zDelete("message:wid:".$wu_id.":user:list",$uid);//删除联系人
            $cache->handler()->del("message:wid:". $wu_id.":user:".$uid.":info");//删除最新消息
            return true;
        }catch (Exception $exception){
           return false;
        }
    }

    /**
     * 获取聊天记录表
     * @param $uid
     * @param $wu_id
     * @param $page
     * @param int $size
     * @return string
     */
    public function getMessageList($uid,$wu_id,$page,$size=10){
        $result = MessageModel::getMessageList($uid,$wu_id,$page,$size);
        $data=  $result->toArray();
        $info = [];
        foreach ($data as $key=>$value) {
            $info[$key]['msg_type'] = $value['msg_type'];
            $info[$key]['content'] = $value['content'];
            $info[$key]['time'] = $value['create_time'];
            $info[$key]['is_read'] = $value['is_read'];
            if ($value['fromuser'] != null) {
                $info[$key]['id'] = $value['fromuser']['id'];
                $info[$key]['nickname'] = $value['fromuser']['nickname'];
                $info[$key]['avatar_url'] = $value['fromuser']['avatar_url'];
            }
            if ($value['fromworkeruser'] != null) {
                $info[$key]['name'] = $value['fromworkeruser']['name'];
                $info[$key]['head_img'] = $value['fromworkeruser']['userimg']['url'];
            }
        }
        return $info;
    }
    /**
     * 获取CRM未读消息条数
     * @param $handler
     * @param $wu_id
     * @param $uid
     * @return int|string
     */
    public function getUnreadList($handler,$wu_id,$uid){
        $i = 0;
        $list =  $handler->zRange("message:wid:".$wu_id.":unread:user:".$uid.":list:1",0,-1);
        if (empty($list)){
            return $i;
        }
        foreach ($list as $item){
            $data = json_decode($item,true);
            if ($data['user_type'] == 1){
                $i++;
            }
        }
        return $i;
    }

    /**
     * 返回消息体格式
     * @param $uid
     * @return string
     */
    private function getMassgeInfo($uid){
        $user = Redis::getInstance()->get(3,'user:'.$uid.':info');
        if (empty($user)){
            $user = User::getUserInfoByUid($uid);
            $user = $user->toArray();
            Redis::getInstance()->set(3,'user:'.$uid.':info',$user,7200);
        }
        $info['id'] = $user['id'];
        $info['url'] = $user['avatar_url'];
        $info['nickname'] = $user['nickname'];
        $info['type'] = 'read';
        $info['content'] = '阅读了你的消息';
        $info['year'] = date("Y-m-d H:i",time());
        $info['stamp'] = strtotime($info['year']);
        return json_encode($info);
    }

}